<?php
declare (strict_types=1);

namespace app\exam\logic\admin;

use app\common\helper\util\Tool;
use app\course\logic\exam\admin\CourseExamLink;
use app\exam\model\admin\PaperAnswerRecord as PaperAnswerRecordModel;
use app\user\logic\user\admin\Account;
use think\annotation\Inject;
use think\Collection;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Model;
use think\Paginator;

/**
 * Class PaperAnswerRecord
 *
 * @package app\exam\logic\admin
 */
class PaperAnswerRecord extends PaperAnswerRecordModel
{
    /**
     * @Inject()
     *
     * @var CourseExamLink
     */
    protected $courseExamLinkLogic;

    /**
     * 获取列表
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/10/14
     *
     * @param array    $map
     * @param null     $phone
     * @param int|null $courseId
     * @return Paginator
     * @throws DbException
     */
    public function getList(array $map = [], $phone = null, ?int $courseId = null)
    {
        $builder = $this->with(['user', 'paperInfo']);
        if ($phone) {
            $userId  = Account::withTrashed()->where('phone', $phone)->value('id');
            $builder = $builder->where('user_id', $userId);
        }

        return $builder->where($map)->paginate($this->getListRows())->each(function ($item) use ($courseId) {
            $item->time_takes = Tool::secsToColonStr($item->time_takes);
            // // 计算是否通过
            $courseId && $item->is_pass = $item->user_score >= $this->courseExamLinkLogic->getPassScore($courseId, $item->paper_id) ? 1 : 0;
        });
    }

    /**
     * 根据用户获取作答的试卷列表
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/10/25
     *
     * @param int $userId
     * @return Paginator
     * @throws DbException
     */
    public function getAnswerRecordByUserId(int $userId)
    {
        return $this->with(['paperInfo'])->where('user_id', $userId)->paginate($this->getListRows())->each(function ($item) {
            $item->time_takes = Tool::secsToColonStr($item->time_takes);
        });
    }

    /**
     * 导出数据
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/11/1
     *
     * @param int        $paperId
     * @param array|null $ids
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getExportData(int $paperId, ?array $ids = [])
    {
        $builder = $this->with(['user'])->where('paper_id', $paperId);
        if ($ids) {
            $builder->whereIn('id', $ids);
        }
        $datas  = $builder->select();
        $xdatas = [];
        foreach ($datas as $data) {
            if ($data->user) {
                $xdatas[] = [
                    'phone'       => $data->user->phone . "\t",
                    // 'paper_title' => $data->paper_title,
                    'paper_score' => $data->paper_score,
                    'user_score'  => $data->user_score,
                    'time_takes'  => $data->time_takes,
                    'topic_count' => $data->topic_count,
                    'right_count' => $data->right_count,
                    'commit_time' => $data->commit_time,
                ];
            }
        }

        return $xdatas;
    }

    /**
     * 根据条件获取作答记录信息
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/11/3
     *
     * @param array $where
     * @return PaperAnswerRecord|array|Model
     */
    public function getInfoByWhere(array $where)
    {
        $data = $this->with(['paperInfo'])->where($where)->findOrFail()->toArray();
        foreach ($data['paper_parts'] as &$paper_part) {
            foreach ($paper_part['value'] as &$item) {
                if (in_array($item['question_type'], [3, 4]) && isset($item['answer_data']) && is_array($item['answer_data'])) {
                    $answer_data = array_values($item['answer_data']);
                    sort($answer_data);
                    $item['answer_data'] = $answer_data;
                }
                if ($item['question_type'] == 7) {
                    $rightAnswer = [];
                    $userAnswers = [];
                    foreach ($item['topics'] as $topic) {
                        $rightAnswer[] = array_column($topic['options'], 'key', 'is_right')[1];
                        $answerKey     = array_column($topic['options'], 'key', 'id');
                        $userAnswers[] = $topic['answer_data'] ? $answerKey[current($topic['answer_data'])] ?? '' : '';
                    }
                    $item['right_answers'] = $rightAnswer;
                    $item['user_answers']  = $userAnswers;
                }
            }
            unset($item);
        }
        unset($paper_part);

        return $data;
    }

    /**
     * 获取指派考试试卷，学员所有考试记录
     *
     * @param int $paperId
     * @param int $userId
     * @return PaperAnswerRecord[]|array|Collection
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getAllAnswerRecordForAssign(int $paperId, int $userId)
    {
        return $this->with(['paperInfo'])
            ->where('paper_id', $paperId)
            ->where('user_id', $userId)
            ->where('is_assign', 1)
            ->select()
            ->each(function ($item) {
                $item->time_takes = Tool::secsToColonStr($item->time_takes);
            });
    }

}
